package com.ruoyi.web.controller.wx_driver;

import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.constant.VQMSConstants;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.core.domain.entity.SysUser;
import com.ruoyi.common.core.page.TableDataInfo;
import com.ruoyi.common.enums.BusinessType;
import com.ruoyi.common.utils.SecurityUtils;
import com.ruoyi.system.service.ISysUserService;
import com.ruoyi.vqms.domain.*;
import com.ruoyi.vqms.service.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;
import org.springframework.web.bind.annotation.*;

import java.util.*;
import java.util.stream.Collectors;

/**
 * 微信访客（司机）
 */
@RestController
@RequestMapping("/wx/reservation")
public class ReservationContoller extends BaseController {

    @Autowired
    private IVQMSQueueReservationService queueReservationService;
    @Autowired
    private IVQMSStorehouseLocationService storehouseLocationService;
    @Autowired
    private IVQMSQueueService queueService;
    @Autowired
    private SendMsgService sendMsgService;
    @Autowired
    private IVQMSQueueAreaService queueAreaService;
    @Autowired
    IVQMSLedService ledService;
    @Autowired
    private ISysUserService sysUserService;
    @Autowired
    private IVQMSVisitRecordYuchiService visitRecordYuchiService;
    @Autowired
    private IVQMSVisitRecordYuchaiService visitRecordYuchaiService;

    /**
     * 查询预约排队列表
     */
    @RequestMapping("/list")
    public TableDataInfo list(VQMSQueueReservation vqmsQueueReservation) {
        startPage();
        List<VQMSQueueReservation> list = queueReservationService.selectList(vqmsQueueReservation);
        if (vqmsQueueReservation.getStatus() == 2) {
            vqmsQueueReservation.setStatus(1);
            list.addAll(queueReservationService.selectList(vqmsQueueReservation));  //预约
        }
        return getDataTable(list);
    }

//    /**
//     * 司机新增预约排队
//     */
//    @Log(title = "司机新增预约排队", businessType = BusinessType.INSERT)
//    @PostMapping("/add")
//    public AjaxResult add(@RequestBody VQMSQueueReservation vqmsQueueReservation) {
////        SysUser sysUser = sysUserService.selectUserById(SecurityUtils.getUserId());
//        vqmsQueueReservation.setCreateBy(vqmsQueueReservation.getDriverPhone());
//        vqmsQueueReservation.setSignTime(new Date());   //默认签到
//
//        //查询司机号码是否在排队，是则自动完成上一条排队任务
//        //先通过车牌找未完成的预约任务
//        VQMSQueueReservation reservation = new VQMSQueueReservation();
//        reservation.setDriverPhone(vqmsQueueReservation.getDriverPhone());  //电话号码
//        reservation.setStatus(VQMSConstants.STATUS_QUEUE_END);       //查询未完成的预约任务(状态不等于未完成)
//        reservation.setUpdateBy(vqmsQueueReservation.getDriverPhone());     //修改人:电话号码，防止司机改名
//        List<VQMSQueueReservation> reservationList = queueReservationService.wxSelectList(reservation);
//        if (!reservationList.isEmpty()) {        //存在未完成的预约任务
//            //先将预约任务状态改为完成
//            reservation = reservationList.get(0);
//            reservation.setStatus(3);   //预约任务已完成
//            int p = queueReservationService.update(reservation);
//
//            //删除玉柴、玉驰对应访客记录
//            VQMSVisitRecordYuchi recordYuchi= visitRecordYuchiService.getReservationId(reservation.getId());
//            if (recordYuchi != null){
//                VQMSVisitRecordYuchai recordYuchai = visitRecordYuchaiService.getReservationId(recordYuchi.getReservationId());
//                if (recordYuchai != null){
//                    int i = visitRecordYuchaiService.delete(new Long[]{recordYuchai.getId()});
//                    if (i != 1){
//                        logger.warn("取消预约-删除对应玉柴访客记录失败");
//                    }
//                }
//
//                int n = visitRecordYuchiService.delete(new Long[]{recordYuchi.getId()});
//                if (n != 1){
//                    logger.warn("取消预约-删除对应玉驰访客记录失败");
//                }
//            } else {
//                logger.info("司机取消预约-未找到对应玉驰访客记录");
//            }
//
//            //再判断是否有未完成排队任务
//            VQMSQueue vqmsQueue = new VQMSQueue();
//            vqmsQueue.setReservationId(reservationList.get(0).getId());
//            List<VQMSQueue> list = queueService.selectList(vqmsQueue);
//            if (!list.isEmpty()) {   //预约存在绑定排队任务
//                int index = list.get(0).getQueueIndex();        //要删除排队任务的排队序号
//                //判断当前任务状态
//                boolean status = false;
//                if (list.get(0).getStatus() == 2) {      //装卸货中
//                    status = true;
//                    return AjaxResult.error("正在装卸货中");
//                }
//                //找到当前排队队列的所有任务，按排队序号递增
//                vqmsQueue.setReservationId(null);
//                vqmsQueue.setAreaId(list.get(0).getAreaId());
//                vqmsQueue.setStatus(VQMSConstants.STATUS_QUEUE_END);    //完成状态
//                List<VQMSQueue> queueList = queueService.selectQueueList(vqmsQueue);     //获取当前排队队列所有任务
//                queueList.sort(Comparator.comparing(VQMSQueue::getQueueIndex));     //按照排队序号进行排序
//
//                //先修改删除任务之后的任务排队序号(index - 1是要删除的任务下标，index是删除对象的下一个)
//                for (int n = index; n < queueList.size(); n++) {
//                    VQMSQueue queue = queueList.get(n);
//                    if (n == index && status) {        //上条任务（删除任务）为装货中
//                        queue.setStatus(2);     //修改为装卸货中
//                        queue.setQueueIndex(queue.getQueueIndex() - 1);  //排队序号前移1位
//                    } else {
//                        queue.setQueueIndex(queue.getQueueIndex() - 1);
//                    }
//                    int up = queueService.update(queue);
//                }
//                //排队任务改为完成
//                vqmsQueue = list.get(0);
//                vqmsQueue.setStatus(3);    //排队任务已完成
//                vqmsQueue.setUpdateBy(vqmsQueueReservation.getDriverPhone());
//                queueService.update(vqmsQueue);
//            }
//        }
//        //上条排队任务完成之后再加新的
//        vqmsQueueReservation.setExpedited((long) 1);    //默认不加急
////        int i = queueReservationService.add(vqmsQueueReservation);
//        int i = queueReservationService.wxAdd(vqmsQueueReservation);
//        //获取预约ID
//        List<VQMSQueueReservation> queueReservationList = queueReservationService.wxSelectList(reservation);
//        if (queueReservationList.isEmpty()){
//            return AjaxResult.error("未找到预约记录");
//        }
//        vqmsQueueReservation = queueReservationList.get(0);
//        if (vqmsQueueReservation == null) {
//            return AjaxResult.error("预约记录异常");
//        }
//
//        if (i == 1){        //新增预约成功，生成玉驰访客记录
//            VQMSVisitRecordYuchi visitRecordYuchi = new VQMSVisitRecordYuchi();
//            visitRecordYuchi.setDriverId(vqmsQueueReservation.getDriverId());
//            visitRecordYuchi.setDriverName(vqmsQueueReservation.getDriverName());
//            visitRecordYuchi.setFactoryId(vqmsQueueReservation.getFactoryId());
//            visitRecordYuchi.setPhone(vqmsQueueReservation.getDriverPhone());
//            visitRecordYuchi.setLicensePlate(vqmsQueueReservation.getLicensePlate());
//            visitRecordYuchi.setCreateBy(vqmsQueueReservation.getDriverName());
//            visitRecordYuchi.setCreateTime(new Date());
//            visitRecordYuchi.setStatus(1);  //进厂
//            visitRecordYuchi.setRegistrationStatus(1);  //已登记
//            visitRecordYuchi.setReservationId(vqmsQueueReservation.getId());
//            try {
//                int n = visitRecordYuchiService.add(visitRecordYuchi);
//            } catch (Exception e){
//                System.out.println("生成玉驰访客记录失败："+e);
//            }
//
//            //复制到玉柴访客记录
//            VQMSVisitRecordYuchai visitRecordYuchai = new VQMSVisitRecordYuchai();
//            visitRecordYuchai.setFactoryId(vqmsQueueReservation.getFactoryId());
//            visitRecordYuchai.setRegisterWarehouse(vqmsQueueReservation.getFactoryName());  //登记仓库
//            visitRecordYuchai.setDriverId(vqmsQueueReservation.getDriverId());
//            visitRecordYuchai.setDriverName(vqmsQueueReservation.getDriverName());
//            visitRecordYuchai.setPhone(vqmsQueueReservation.getDriverPhone());
//            visitRecordYuchai.setLicensePlate(vqmsQueueReservation.getLicensePlate());
//            visitRecordYuchai.setCreateBy(vqmsQueueReservation.getDriverName());
//            visitRecordYuchai.setCreateTime(new Date());
//            visitRecordYuchai.setRegistrationStatus(1); //已登记
//            visitRecordYuchai.setReservationId(vqmsQueueReservation.getId());
//            try {
//                int a = visitRecordYuchaiService.add(visitRecordYuchai);
//            } catch (Exception e){
//                System.out.println("生成玉柴访客记录失败："+e);
//            }
//
//        }
//
//        //发送模板消息
////        if (i == 1) {        //新增成功
////            //查询对应排队任务获取信息
////            VQMSQueue vqmsQueue = new VQMSQueue();
////            vqmsQueue.setReservationId(vqmsQueueReservation.getId());
////            List<VQMSQueue> list = queueService.selectList(vqmsQueue);
////            VQMSQueueArea vqmsQueueArea = queueAreaService.getById(list.get(0).getAreaId());
////            String wxOpenId = vqmsQueueReservation.getWxOpenId();
////            String reservationId = String.valueOf(list.get(0).getReservationId());  //签到编号
////            String status = "已叫号";
////            String areaName = vqmsQueueArea.getName().replace("队列", "");      //月台编号
////            String driverName = vqmsQueueReservation.getDriverName();               //司机姓名
////            String licensePlate = vqmsQueueReservation.getLicensePlate();           //车牌号
////            sendMsgService.send_msg(wxOpenId, reservationId, status, areaName, driverName, licensePlate);
////            //刷新LED大屏
////            try {
////                ledService.flushLesScreenData(vqmsQueueArea.getId());
////            } catch (Exception e) {
////                logger.error("司机新增排队刷新LED大屏失败");
////                e.printStackTrace();
////            }
////        } else {        //只记录不排队，直接完成新增预约任务
////            List<VQMSQueueReservation> reservations = queueReservationService.selectList(reservation);
////            if (!reservations.isEmpty()) {   //存在未完成预约任务
////                reservation.setStatus(3);   //完成
////                reservation.setCompleteTime(new Date());
////                reservation.setId(reservations.get(0).getId());
////                queueReservationService.update(reservation);
////            }
////        }
//
//        return AjaxResult.success();
//    }

    /**
     * 司机新增预约排队
     */
    @Log(title = "司机新增预约排队", businessType = BusinessType.INSERT)
    @PostMapping("/add")
    @Transactional(rollbackFor = Exception.class)
    public AjaxResult add(@RequestBody VQMSQueueReservation reservation) {
        try {
            // 设置预约基础信息
            reservation.setCreateBy(reservation.getDriverPhone());
            reservation.setSignTime(new Date()); // 默认签到
            reservation.setExpedited((long) 1);  // 默认不加急

            // 处理司机未完成的预约任务
            VQMSQueueReservation query = new VQMSQueueReservation();
            query.setDriverPhone(reservation.getDriverPhone());
            query.setStatus(VQMSConstants.STATUS_QUEUE_END);
            query.setUpdateBy(reservation.getDriverPhone());

            List<VQMSQueueReservation> unfinishedReservations = queueReservationService.wxSelectList(query);
            if (!unfinishedReservations.isEmpty()) {
                VQMSQueueReservation unfinished = unfinishedReservations.get(0);

                if (VQMSConstants.STATUS_RESERVATION_NO_SIGN == unfinished.getStatus()) {
                    // 处理未确认预约：删除相关记录
                    VQMSVisitRecordYuchi yuchiRecord = visitRecordYuchiService.getReservationId(unfinished.getId());
                    if (yuchiRecord != null) {
                        VQMSVisitRecordYuchai yuchaiRecord = visitRecordYuchaiService.getReservationId(yuchiRecord.getReservationId());
                        if (yuchaiRecord != null) {
                            visitRecordYuchaiService.delete(new Long[]{yuchaiRecord.getId()});
                        }
                        visitRecordYuchiService.delete(new Long[]{yuchiRecord.getId()});
                    }
                    queueReservationService.delete(new Long[]{unfinished.getId()});
                } else if (VQMSConstants.STATUS_RESERVATION_SIGN == unfinished.getStatus()) {
                    // 处理已确认预约：更新为完成状态
                    VQMSVisitRecordYuchi yuchiRecord = visitRecordYuchiService.getReservationId(unfinished.getId());
                    if (yuchiRecord != null) {
                        // 更新玉柴记录
                        VQMSVisitRecordYuchai yuchaiRecord = visitRecordYuchaiService.getReservationId(yuchiRecord.getReservationId());
                        if (yuchaiRecord != null) {
                            yuchaiRecord.setRegistrationStatus(2);
                            yuchaiRecord.setConfirmedBy(1);
                            if (visitRecordYuchaiService.update(yuchaiRecord) != 1) {
                                logger.warn("更新玉柴访客记录失败, id:{}", yuchaiRecord.getId());
                            }
                        }
                        // 更新玉驰记录
                        yuchiRecord.setRegistrationStatus(2);
                        yuchiRecord.setConfirmedBy(1);
                        if (visitRecordYuchiService.update(yuchiRecord) != 1) {
                            logger.warn("更新玉驰访客记录失败, id:{}", yuchiRecord.getId());
                        }
                    } else {
                        logger.info("未找到对应玉驰访客记录, reservationId:{}", unfinished.getId());
                    }

                    // 处理关联的排队任务
                    VQMSQueue queueQuery = new VQMSQueue();
                    queueQuery.setReservationId(unfinished.getId());
                    List<VQMSQueue> relatedQueues = queueService.selectList(queueQuery);

                    if (!relatedQueues.isEmpty()) {
                        VQMSQueue targetQueue = relatedQueues.get(0);
                        boolean isLoading = VQMSConstants.STATUS_QUEUE_LOADING == targetQueue.getStatus();
                        int targetIndex = targetQueue.getQueueIndex();

                        // 获取同区域排队任务并排序
                        VQMSQueue areaQuery = new VQMSQueue();
                        areaQuery.setAreaId(targetQueue.getAreaId());
                        areaQuery.setStatus(VQMSConstants.STATUS_QUEUE_END);
                        List<VQMSQueue> areaQueues = queueService.selectQueueList(areaQuery);
                        areaQueues.sort(Comparator.comparing(VQMSQueue::getQueueIndex));

                        // 更新后续任务序号
                        for (int i = targetIndex; i < areaQueues.size(); i++) {
                            VQMSQueue queue = areaQueues.get(i);
                            queue.setQueueIndex(queue.getQueueIndex() - 1);
                            if (i == targetIndex && isLoading) {
                                queue.setStatus(VQMSConstants.STATUS_QUEUE_LOADING);
                            }
                            queueService.update(queue);
                        }

                        // 标记当前排队任务为已完成
                        targetQueue.setStatus(VQMSConstants.STATUS_QUEUE_END);
                        targetQueue.setUpdateBy(reservation.getDriverPhone());
                        queueService.update(targetQueue);
                    }

                    // 更新预约状态为已完成
                    unfinished.setStatus(VQMSConstants.STATUS_QUEUE_END);
                    queueReservationService.update(unfinished);
                }
            }

            // 新增预约记录
            reservation.setStatus(2);   //默认已签到
            int addResult = queueReservationService.wxAdd(reservation);
            if (addResult != 1) {
                return AjaxResult.error("新增预约失败");
            }

            // 获取新增的预约记录
            VQMSQueueReservation searchParam = new VQMSQueueReservation();
            searchParam.setDriverPhone(reservation.getDriverPhone());
            searchParam.setStatus(VQMSConstants.STATUS_QUEUE_END);
            searchParam.setUpdateBy(reservation.getDriverPhone());

            List<VQMSQueueReservation> result = queueReservationService.wxSelectList(searchParam);
            if (result.isEmpty()) {
                return AjaxResult.error("未找到预约记录");
            }
            VQMSQueueReservation newReservation = result.get(0);

            //生成新排队任务
            int i = queueService.wxAdd(newReservation);
            if (i == 1) {        //新增排队任务成功
                //查询对应排队任务获取信息
                VQMSQueue vqmsQueue = new VQMSQueue();
                vqmsQueue.setReservationId(newReservation.getId());
                List<VQMSQueue> list = queueService.selectList(vqmsQueue);
                if (list.isEmpty()){
                    return AjaxResult.error("发送提醒消息-未找到排队任务");
                }
                VQMSQueueArea vqmsQueueArea = queueAreaService.getById(list.get(0).getAreaId());
                //刷新LED大屏
                try {
                    ledService.flushLesScreenData(vqmsQueueArea.getId());
                } catch (Exception e) {
                    logger.error("司机新增排队刷新LED大屏失败");
                    e.printStackTrace();
                }
            }

            // 创建玉驰访客记录
            try {
                VQMSVisitRecordYuchi yuchiRecord = new VQMSVisitRecordYuchi();
                yuchiRecord.setDriverId(reservation.getDriverId());
                yuchiRecord.setDriverName(reservation.getDriverName());
                yuchiRecord.setFactoryId(reservation.getFactoryId());
                yuchiRecord.setPhone(reservation.getDriverPhone());
                yuchiRecord.setLicensePlate(reservation.getLicensePlate());
                yuchiRecord.setCreateBy(reservation.getDriverName());
                yuchiRecord.setCreateTime(new Date());
                yuchiRecord.setStatus(1);
                yuchiRecord.setRegistrationStatus(2);
                yuchiRecord.setConfirmedBy(1);
                yuchiRecord.setConfirmedTime(new Date());
                yuchiRecord.setReservationId(newReservation.getId());
                visitRecordYuchiService.add(yuchiRecord);
            } catch (Exception e) {
                logger.error("生成玉驰访客记录失败", e);
            }

            // 创建玉柴访客记录
            try {
                VQMSVisitRecordYuchai yuchaiRecord = new VQMSVisitRecordYuchai();
                yuchaiRecord.setFactoryId(reservation.getFactoryId());
                yuchaiRecord.setRegisterWarehouse(reservation.getFactoryName());
                yuchaiRecord.setDriverId(reservation.getDriverId());
                yuchaiRecord.setDriverName(reservation.getDriverName());
                yuchaiRecord.setPhone(reservation.getDriverPhone());
                yuchaiRecord.setLicensePlate(reservation.getLicensePlate());
                yuchaiRecord.setCreateBy(reservation.getDriverName());
                yuchaiRecord.setIsComputer(reservation.getIsComputer());
                yuchaiRecord.setClothing(reservation.getClothing());
                yuchaiRecord.setSex(reservation.getSex());
                yuchaiRecord.setVisitCompany(reservation.getVisitCompany());
                yuchaiRecord.setVisitName(reservation.getVisitName());
                yuchaiRecord.setVisitReason(reservation.getVisitReason());
                yuchaiRecord.setWorkCompany(reservation.getWorkCompany());
                yuchaiRecord.setCreateTime(new Date());
                yuchaiRecord.setRegistrationStatus(2);
                yuchaiRecord.setConfirmedBy(1);
                yuchaiRecord.setConfirmedTime(new Date());
                yuchaiRecord.setReservationId(newReservation.getId());
                visitRecordYuchaiService.add(yuchaiRecord);
            } catch (Exception e) {
                logger.error("生成玉柴访客记录失败", e);
            }

            return AjaxResult.success();
        } catch (Exception e) {
            logger.error("添加预约异常", e);
            return AjaxResult.error("系统异常，请稍后重试");
        }
    }

//    public AjaxResult add(@RequestBody VQMSQueueReservation vqmsQueueReservation) {
//        VQMSQueueReservation queueReservation = vqmsQueueReservation;
//        vqmsQueueReservation.setCreateBy(vqmsQueueReservation.getDriverPhone());
//        vqmsQueueReservation.setSignTime(new Date());   //默认签到
//
//        //查询司机号码是否在排队，是则自动完成上一条排队任务
//        //先通过车牌找未完成的预约任务
//        VQMSQueueReservation reservation = new VQMSQueueReservation();
//        reservation.setDriverPhone(vqmsQueueReservation.getDriverPhone());  //电话号码
//        reservation.setStatus(VQMSConstants.STATUS_QUEUE_END);       //查询未完成的预约任务(状态不等于未完成)
//        reservation.setUpdateBy(vqmsQueueReservation.getDriverPhone());     //修改人:电话号码，防止司机改名
//        VQMSQueueReservation reservation1 = reservation;
//        List<VQMSQueueReservation> reservationList = queueReservationService.wxSelectList(reservation);
//        if (!reservationList.isEmpty()) {        //存在未完成的预约任务
//            //先将预约任务状态改为完成
//            reservation = reservationList.get(0);
//            if (reservation.getStatus() == 1){  //预约未确认，删除原记录
//                VQMSVisitRecordYuchi recordYuchi= visitRecordYuchiService.getReservationId(reservation.getId());
//                if (recordYuchi != null){
//                    VQMSVisitRecordYuchai recordYuchai = visitRecordYuchaiService.getReservationId(recordYuchi.getReservationId());
//                    if (recordYuchai != null){
//                        Long[] ids = {recordYuchai.getId()};
//                        int n = visitRecordYuchaiService.delete(ids);   //删除玉柴
//                    }
//                }
//                Long[] ids = {recordYuchi.getId()};
//                int i = visitRecordYuchiService.delete(ids);    //删除玉驰
//
//                Long[] reIds = {reservation.getId()};
//                int q = queueReservationService.delete(reIds);
//            } else if (reservation.getStatus() == 2){
//                //完成玉柴、玉驰对应访客记录
//                VQMSVisitRecordYuchi recordYuchi= visitRecordYuchiService.getReservationId(reservation.getId());
//                if (recordYuchi != null){
//                    VQMSVisitRecordYuchai recordYuchai = visitRecordYuchaiService.getReservationId(recordYuchi.getReservationId());
//                    if (recordYuchai != null){
////                    int i = visitRecordYuchaiService.delete(new Long[]{recordYuchai.getId()});
//                        recordYuchai.setRegistrationStatus(2);      //已确认
//                        recordYuchai.setConfirmedBy(1);     //本人确认
//                        int i = visitRecordYuchaiService.update(recordYuchai);
//                        if (i != 1){
//                            logger.warn("完成预约-完成对应玉柴访客记录失败");
//                        }
//                    }
//
//                    recordYuchi.setRegistrationStatus(2);
//                    recordYuchi.setConfirmedBy(1);
////                int n = visitRecordYuchiService.delete(new Long[]{recordYuchi.getId()});
//                    int n = visitRecordYuchiService.update(recordYuchi);
//                    if (n != 1){
//                        logger.warn("完成预约-删除对应玉驰访客记录失败");
//                    }
//                } else {
//                    logger.info("司机新增预约-未找到对应玉驰访客记录");
//                }
//
//                //再判断是否有未完成排队任务
//                VQMSQueue vqmsQueue = new VQMSQueue();
//                vqmsQueue.setReservationId(reservationList.get(0).getId());
//                List<VQMSQueue> list = queueService.selectList(vqmsQueue);
//                if (!list.isEmpty()) {   //预约存在绑定排队任务
//                    int index = list.get(0).getQueueIndex();        //要删除排队任务的排队序号
//                    //判断当前任务状态
//                    boolean status = false;
//                    if (list.get(0).getStatus() == 2) {      //装卸货中
//                        status = true;
////                    return AjaxResult.error("正在装卸货中");
//                    }
//
//                    //找到当前排队队列的所有任务，按排队序号递增
//                    vqmsQueue.setReservationId(null);
//                    vqmsQueue.setAreaId(list.get(0).getAreaId());
//                    vqmsQueue.setStatus(VQMSConstants.STATUS_QUEUE_END);    //完成状态
//                    List<VQMSQueue> queueList = queueService.selectQueueList(vqmsQueue);     //获取当前排队队列所有任务
//                    queueList.sort(Comparator.comparing(VQMSQueue::getQueueIndex));     //按照排队序号进行排序
//
//                    //先修改删除任务之后的任务排队序号(index - 1是要删除的任务下标，index是删除对象的下一个)
//                    for (int n = index; n < queueList.size(); n++) {
//                        VQMSQueue queue = queueList.get(n);
//                        if (n == index && status) {        //上条任务（删除任务）为装货中
//                            queue.setStatus(2);     //修改为装卸货中
//                            queue.setQueueIndex(queue.getQueueIndex() - 1);  //排队序号前移1位
//                        } else {
//                            queue.setQueueIndex(queue.getQueueIndex() - 1);
//                        }
//                        int up = queueService.update(queue);
//                    }
//                    //排队任务改为完成
//                    vqmsQueue = list.get(0);
//                    vqmsQueue.setStatus(3);    //排队任务已完成
//                    vqmsQueue.setUpdateBy(vqmsQueueReservation.getDriverPhone());
//                    queueService.update(vqmsQueue);
//                }
//                reservation.setStatus(3);   //预约任务已完成
//                int p = queueReservationService.update(reservation);
//            }
//
//        }
//        //上条排队任务完成之后再加新的
//        vqmsQueueReservation.setExpedited((long) 1);    //默认不加急
////        int i = queueReservationService.add(vqmsQueueReservation);
//        int i = queueReservationService.wxAdd(vqmsQueueReservation);
//        //重新查询，获取预约ID
//        List<VQMSQueueReservation> queueReservationList = queueReservationService.wxSelectList(reservation1);
//        if (queueReservationList.isEmpty()){
//            return AjaxResult.error("预约-未找到预约记录");
//        }
//        vqmsQueueReservation = queueReservationList.get(0);     //会重置玉柴表的一些字段
//        if (vqmsQueueReservation == null) {
//            return AjaxResult.error("预约记录异常");
//        }
//
//        if (i == 1){        //新增预约成功，生成玉驰访客记录
//            VQMSVisitRecordYuchi visitRecordYuchi = new VQMSVisitRecordYuchi();
//            visitRecordYuchi.setDriverId(queueReservation.getDriverId());
//            visitRecordYuchi.setDriverName(queueReservation.getDriverName());
//            visitRecordYuchi.setFactoryId(queueReservation.getFactoryId());
//            visitRecordYuchi.setPhone(queueReservation.getDriverPhone());
//            visitRecordYuchi.setLicensePlate(queueReservation.getLicensePlate());
//            visitRecordYuchi.setCreateBy(queueReservation.getDriverName());
//            visitRecordYuchi.setCreateTime(new Date());
//            visitRecordYuchi.setStatus(1);  //进厂
//            visitRecordYuchi.setRegistrationStatus(1);  //已登记
//            visitRecordYuchi.setReservationId(vqmsQueueReservation.getId());
//            try {
//                int n = visitRecordYuchiService.add(visitRecordYuchi);
//            } catch (Exception e){
//                System.out.println("生成玉驰访客记录失败："+e);
//            }
//
//            //复制到玉柴访客记录
//            VQMSVisitRecordYuchai visitRecordYuchai = new VQMSVisitRecordYuchai();
//            visitRecordYuchai.setFactoryId(queueReservation.getFactoryId());
//            visitRecordYuchai.setRegisterWarehouse(queueReservation.getFactoryName());  //登记仓库
//            visitRecordYuchai.setDriverId(queueReservation.getDriverId());
//            visitRecordYuchai.setDriverName(queueReservation.getDriverName());
//            visitRecordYuchai.setPhone(queueReservation.getDriverPhone());
//            visitRecordYuchai.setLicensePlate(queueReservation.getLicensePlate());
//            visitRecordYuchai.setCreateBy(queueReservation.getDriverName());
//            visitRecordYuchai.setIsComputer(queueReservation.getIsComputer());
//            visitRecordYuchai.setClothing(queueReservation.getClothing());
//            visitRecordYuchai.setSex(queueReservation.getSex());
//            visitRecordYuchai.setVisitCompany(queueReservation.getVisitCompany());
//            visitRecordYuchai.setVisitName(queueReservation.getVisitName());
//            visitRecordYuchai.setVisitReason(queueReservation.getVisitReason());
//            visitRecordYuchai.setWorkCompany(queueReservation.getWorkCompany());
//            visitRecordYuchai.setCreateTime(new Date());
//            visitRecordYuchai.setRegistrationStatus(1); //已登记
//            visitRecordYuchai.setReservationId(vqmsQueueReservation.getId());
//            try {
//                int a = visitRecordYuchaiService.add(visitRecordYuchai);
//            } catch (Exception e){
//                System.out.println("生成玉柴访客记录失败："+e);
//            }
//        }
//        return AjaxResult.success();
//    }

    /**
     * 司机确认预约
     */
    @Log(title = "司机确认预约", businessType = BusinessType.INSERT)
    @PostMapping("/confirmedQueue")
    public AjaxResult confirmedQueue(@RequestBody VQMSQueueReservation vqmsQueueReservation){
        //确认预约
        vqmsQueueReservation.setStatus(2);
        int m = queueReservationService.update(vqmsQueueReservation);
        if (m != 1){
            return AjaxResult.error("司机确认预约失败");
        }
        int reservationStatus = 0;     //预约状态

        //确认玉驰访客记录
        VQMSVisitRecordYuchi visitRecordYuchi = new VQMSVisitRecordYuchi();
//        visitRecordYuchi.setDriverId(vqmsQueueReservation.getDriverId());
//        visitRecordYuchi.setPhone(vqmsQueueReservation.getDriverPhone());
//        visitRecordYuchi.setRegistrationStatus(1);      //已登记
        visitRecordYuchi.setReservationId(vqmsQueueReservation.getId());
        List<VQMSVisitRecordYuchi> yuchiList = visitRecordYuchiService.selectList(visitRecordYuchi);
        if (!yuchiList.isEmpty()){  //有未确认的记录
            visitRecordYuchi = yuchiList.get(0);
            visitRecordYuchi.setConfirmedBy(1); //本人确认
            visitRecordYuchi.setConfirmedTime(new Date());
            visitRecordYuchi.setRegistrationStatus(2);      //已确认
            visitRecordYuchi.setUpdateBy(vqmsQueueReservation.getDriverName());
            int n = visitRecordYuchiService.update(visitRecordYuchi);
        } else {
            logger.error("司机确认预约-同步玉驰访问记录失败，未查到预约记录");
        }

        //确认玉柴访客记录
        VQMSVisitRecordYuchai visitRecordYuchai = new VQMSVisitRecordYuchai();
//        visitRecordYuchai.setDriverId(vqmsQueueReservation.getDriverId());
//        visitRecordYuchai.setPhone(vqmsQueueReservation.getDriverPhone());
//        visitRecordYuchai.setRegistrationStatus(1);     //已登记
        visitRecordYuchai.setReservationId(vqmsQueueReservation.getId());
        List<VQMSVisitRecordYuchai> yuchaiList = visitRecordYuchaiService.selectList(visitRecordYuchai);
        if (!yuchaiList.isEmpty()){
            visitRecordYuchai = yuchaiList.get(0);
            visitRecordYuchai.setConfirmedBy(1); //本人确认
            visitRecordYuchai.setConfirmedTime(new Date());
            visitRecordYuchai.setRegistrationStatus(2);      //已确认
            visitRecordYuchai.setUpdateBy(vqmsQueueReservation.getDriverName());
            int n = visitRecordYuchaiService.update(visitRecordYuchai);
        } else {
            logger.error("司机确认预约-同步玉柴访问记录失败，未查到预约记录");
        }

        //生成排队信息
        int i = queueService.wxAdd(vqmsQueueReservation);
        //发送模板消息
        if (i == 1) {        //新增排队任务成功
            reservationStatus = 2;     //已确认
            //查询对应排队任务获取信息
            VQMSQueue vqmsQueue = new VQMSQueue();
            vqmsQueue.setReservationId(vqmsQueueReservation.getId());
            List<VQMSQueue> list = queueService.selectList(vqmsQueue);
            if (list.isEmpty()){
                return AjaxResult.error("发送提醒消息-未找到排队任务");
            }
            VQMSQueueArea vqmsQueueArea = queueAreaService.getById(list.get(0).getAreaId());
            String wxOpenId = vqmsQueueReservation.getWxOpenId();
            String reservationId = String.valueOf(list.get(0).getReservationId());  //签到编号
            String status = "已叫号";
            String areaName = vqmsQueueArea.getName().replace("队列", "");      //月台编号
            String driverName = vqmsQueueReservation.getDriverName();               //司机姓名
            String licensePlate = vqmsQueueReservation.getLicensePlate();           //车牌号
            sendMsgService.send_msg(wxOpenId, reservationId, status, areaName, driverName, licensePlate);
            //刷新LED大屏
            try {
                ledService.flushLesScreenData(vqmsQueueArea.getId());
            } catch (Exception e) {
                logger.error("司机新增排队刷新LED大屏失败");
                e.printStackTrace();
            }
        } else {        //新增排队任务失败，直接完成预约任务
            reservationStatus = 3;     //已完成
        }
        vqmsQueueReservation.setStatus(reservationStatus);

        return AjaxResult.success();
    }


    /**
     * 查询仓库库位列表(不分页)
     */
    @RequestMapping("/getLocationList")
    public AjaxResult getList(VQMSStorehouseLocation vqmsStorehouseLocation) {
        return AjaxResult.success(storehouseLocationService.selectList(vqmsStorehouseLocation));
    }

    /**
     * 司机取消预约排队
     */
    @Log(title = "取消预约排队", businessType = BusinessType.DELETE)
    @PostMapping("/remove")
    public AjaxResult removeQueueReservation(@RequestBody VQMSQueueReservation vqmsQueueReservation) {

        Long[] ids = new Long[1];
        ids[0] = vqmsQueueReservation.getId();
        //查询司机取消的预约任务是否在排队装卸货中
        VQMSQueue vqmsQueue = queueService.getByReservationId(vqmsQueueReservation.getId());
        if(vqmsQueue != null){
            if (vqmsQueue.getStatus() == VQMSConstants.STATUS_QUEUE_LOADING) {   //装卸货中
                return AjaxResult.error("正在装卸货中");
            }
        } else {
            logger.warn("当前预约无排队任务");
        }

        //删除对应玉驰访客记录

        VQMSVisitRecordYuchi recordYuchi= visitRecordYuchiService.getReservationId(vqmsQueueReservation.getId());
        if (recordYuchi != null){
            VQMSVisitRecordYuchai recordYuchai = visitRecordYuchaiService.getReservationId(recordYuchi.getReservationId());
            if (recordYuchai != null){
                int i = visitRecordYuchaiService.delete(new Long[]{recordYuchai.getId()});
                if (i != 1){
                    logger.warn("取消预约-删除对应玉柴访客记录失败");
                }
            }

            int n = visitRecordYuchiService.delete(new Long[]{recordYuchi.getId()});
            if (n != 1){
                logger.warn("取消预约-删除对应玉驰访客记录失败");
            }
        } else {
            logger.info("司机取消预约-未找到对应玉驰访客记录");
        }



        return AjaxResult.success(queueReservationService.delete(ids));

//        //查询预约生成排队任务
//        VQMSQueue vqmsQueue = new VQMSQueue();
//        vqmsQueue.setReservationId(vqmsQueueReservation.getId());
//        List<VQMSQueue> list=queueService.selectList(vqmsQueue);
//
//        if (!list.isEmpty()){   //预约存在绑定排队任务
//            int index = list.get(0).getQueueIndex();        //要删除排队任务的排队序号
//            //判断当前任务状态
//            boolean status = false;
//            if (list.get(0).getStatus() == 2){      //装卸货中
//                status = true;
//            }
//        //找到当前排队队列的所有任务，按排队序号递增
//            vqmsQueue.setReservationId(null);
//            vqmsQueue.setAreaId(list.get(0).getAreaId());
//            List<VQMSQueue> queueList = queueService.selectList(vqmsQueue);     //获取当前排队队列所有任务
//            queueList.sort(Comparator.comparing(VQMSQueue::getQueueIndex));     //按照排队序号进行排序
//
//            //先修改删除任务之后的任务排队序号(index - 1是要删除的任务下标，index是删除对象的下一个)
//            for (int n = index;n<queueList.size();n ++){
//                VQMSQueue queue = queueList.get(n);
//                if (n==index && status){        //上条任务（删除任务）为装货中
//                    queue.setStatus(2);     //修改为装卸货中
//                    queue.setQueueIndex(queue.getQueueIndex() -1);  //排队序号前移1位
//                } else {
//                    queue.setQueueIndex(queue.getQueueIndex() -1);
//                }
//                int up = queueService.update(queue);
//            }
//            //修改完之后删除任务
//            Long[] ids = new Long[1];
//            ids[0] = list.get(0).getId();
//            int de = queueService.delete(ids);
//            //删除预约
//            ids[0] = vqmsQueueReservation.getId();
//            int de2 = queueReservationService.delete(ids);
//        } else {
//            return AjaxResult.error("取消预约失败");
//        }

//        return AjaxResult.success();
    }

    /**
     * 查询司机是否有未完成预约
     */
    @RequestMapping("/selectQueue")
    public AjaxResult selectQueue(VQMSQueueReservation vqmsQueueReservation) {
        List<VQMSQueueReservation> list = queueReservationService.selectList(vqmsQueueReservation);     //预约
        vqmsQueueReservation.setStatus(2);
        list.addAll(queueReservationService.selectList(vqmsQueueReservation));  //确认
        if (list.isEmpty()) {       //司机不存在的预约
            return AjaxResult.success(200);
        } else {        //司机存在排队的预约
            return AjaxResult.success(String.valueOf(201),list);
        }
    }


}
